import datetime
import os.path

from selenium.webdriver import ActionChains, Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from common.mylogger import logger
from config.path import img_path


class Basepage():
    host = ""

    def __init__(self, driver: Chrome):
        self.driver = driver

    def goto(self, url):
        """访问页面"""
        if url.startswith('http'):
            self.driver.get(url)
        else:
            url = self.host + url
            self.driver.get(url)
        logger.info(f"进入网页: {url}")
        return self

    def click(self, locator: tuple, force=False):
        """点击，可以选择点击"""
        try:
            el = self.driver.find_element(*locator)
            # 有时候元素点击不生效，需要强制点击
            if not force:
                self.driver.execute_script("arguments[0].click()", el)
            else:
                self.driver.execute_script("arguments[0].click({force: true})", el)
            logger.info(f"元素已经被点击:{locator}")
            return self
        except NoSuchElementException as e:
            logger.error(f"元素无法定位:{e}")

    def fill(self, locator, text):
        """输入内容"""
        try:
            elem = self.driver.find_element(*locator)
            elem.send_keys(text)
            logger.info(f"元素被输入内容：{locator}")
            return self
        except NoSuchElementException as e:
            logger.error(f"元素无法定位: {e}")

    def clear(self, locator):
        """清除内容"""
        try:
            elem = self.driver.find_element(*locator)
            elem.clear()
            return self
        except NoSuchElementException as e:
            logger.error(f"元素无法定位:{e}")

    def get_attribute(self, locator, attr_name):
        """获取元素属性"""
        try:
            elem = self.driver.find_element(*locator)
            return elem.get_attribute(attr_name)
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    @property
    def name(self, locator):
        """获取元素的name属性"""
        return self.get_attribute(locator, 'name')

    @property
    def text(self, locator):
        """获取元素的text属性"""
        return self.get_attribute(locator, "text")

    def double_click(self, locator):
        """双击操作"""
        try:
            el = self.driver.find_element(*locator)
            action = ActionChains(self.driver)
            action.double_click(el).perform()
            return self
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def grag_and_drop(self, start_locator, end_locator):
        """鼠标拖拽"""
        try:
            elem_start = self.driver.find_element(*start_locator)
            elem_end = self.driver.find_element(*end_locator)
            action = ActionChains(self.driver)
            action.double_click(elem_start, elem_end).perform()
            return self
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def hover(self, locator):
        """鼠标悬停"""
        try:
            el = self.driver.find_element(*locator)
            action = ActionChains(self.driver)
            action.move_to_element(el).perform()
            return self
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def wait_visible(self, locator, timeout=10, poll=0.2):
        """等待元素可见"""
        try:
            wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll)
            el = wait.until(expected_conditions.visibility_of_element_located(locator))
            return el
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def wait_prescence(self, locator, timeout=10, poll=0.2):
        """等待元素加载"""
        try:
            wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll)
            el = wait.until(expected_conditions.presence_of_element_located(locator))
            return el
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def wait_clickble(self, locator, timeout=10, poll=0.2):
        """等待元素被点击"""
        try:
            wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll)
            el = wait.until(expected_conditions.element_to_be_clickable(locator))
            return el
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def switch_to_frame(self, reference, timeout=10, poll=0.2):
        """iframe切换"""
        """reference可以是iframe的name， element对象，索引，locator"""
        try:
            if not reference:
                return self.driver.switch_to.parent_frame()
            wait = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll)
            el = wait.until(expected_conditions.frame_to_be_available_and_switch_to_it(reference))
            return el
        except NoSuchElementException as e:
            print(f"没有这个元素:{e}")

    def screenshot(self):
        """截图"""
        # 获取现在的时间
        current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        file_name = f"屏幕截图-{current_time}.png"
        file_path = os.path.join(img_path, file_name)
        self.driver.get_screenshot_as_file(file_path)
        return self


if __name__ == '__main__':
    diver = Chrome()
    d = Basepage(diver)
    d.host = "https://www.baidu.com"
    d.goto('')
    d.fill(("id", "kw"), "孤勇者")
    d.hover(("id", "su"))
    d.click(("id", "su"))
    d.screenshot()


